package com.kob.backend.service.impl.user.account;

import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.account.InfoService;
import com.kob.backend.vo.UserVo;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author cyz
 * @version 1.0
 * @date 2023/1/13 10:49
 */
//一定要加这个注解，等于是注入了spring容器当中未来使用接口的时候可以直接使用autowired注解直接自动注入
@Service
public class InfoServiceImpl implements InfoService {

    @Resource
    UserMapper userMapper;
    @Override
    public Map<String, String> getinfo() {

        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();


        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        Map<String, String> map = new HashMap<>();
        map.put("error_message", "success");
        map.put("id", user.getId().toString());
        map.put("username", user.getUsername());
        map.put("photo", user.getPhoto());

        return map;
    }

    @Override
    public Map<String, Object> getTypes() {
        return null;
    }

    @Override
    public Map<String, List<UserVo>> getUsers() {
        Map<String, List<UserVo>> ans = new HashMap<>();
        // 返回三种类型的users 各自的集合
        List<User> users = userMapper.selectList(null);

        List<UserVo> Admins = new ArrayList<>();
        List<UserVo> RSUs = new ArrayList<>();
        List<UserVo> EVs = new ArrayList<>();

        for(User user : users) {
            Integer type = user.getType();
            UserVo userVo = new UserVo();
            userVo.setUsername(user.getUsername());
            userVo.setId(user.getId());
            userVo.setType(user.getType());
            if(type == 1) Admins.add(userVo);
            else if(type == 2) RSUs.add(userVo);
            else if(type == 3) EVs.add(userVo);;
        }
        ans.put("Admins", Admins);
        ans.put("RSUs", RSUs);
        ans.put("EVs", EVs);
        return ans;
    }
}
